package com.ushier.shop.drugstore.controller;

import com.ushier.shop.drugstore.bean.Drug;
import com.ushier.shop.drugstore.bean.Drug;
import com.ushier.shop.drugstore.bean.ResponseMessageBean;
import com.ushier.shop.drugstore.dao.OrderDAO;
import com.ushier.shop.drugstore.util.StringUtil;
import com.ushier.shop.drugstore.vo.OrderVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/manage/order")
public class ManageOrderServlet extends HttpServlet {

    private OrderDAO dao = new OrderDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        String action = req.getParameter("action");

        if(StringUtil.isNull(action)){
            out.print(JSONObject.fromObject(ResponseMessageBean.error("缺少参数")));
            return;
        }


        switch (action){
            case "list":
                List<OrderVO> orderVOList = dao.list();
                out.print(JSONObject.fromObject(ResponseMessageBean.success(orderVOList)));
                return;
            case "add":
                Integer uid = (Integer) req.getSession().getAttribute("uid");
                List<Drug> list = (List<Drug>) req.getSession().getAttribute("list_" + uid);
                if(null == list || list.isEmpty()){
                    out.print(JSONObject.fromObject(ResponseMessageBean.error("购物车没有任何商品哦！")));
                    return;
                }
                boolean insert = dao.insert(uid, UUID.randomUUID().toString(), new Date(), JSONArray.fromObject(list).toString());
                if(insert){
                    req.getSession().removeAttribute("list_" + uid);
                    BigDecimal sumPrice = new BigDecimal(0);
                    for(Drug item : list){
                        sumPrice = sumPrice.add(item.getPrice().multiply(new BigDecimal(item.getCount())));
                    }
                    out.print(JSONObject.fromObject(ResponseMessageBean.success(insert, "共支付" +sumPrice + "元")));
                }
                return;
            default:
                break;
        }


    }
}
